'''
项目名称：数据采集器
固件版本信息:V1.0.0
对应软件版:V
日期:2025-11-15
作者:Hoyt
'''

import utime as time
import rtc
import app_config
import hmi_drv
import serial_port232
import sensor_interface
import m485Drv
import tfcard
# import yun_network
# import power
# import led_drv
# import sleep_mode




sensor_instan = None
rtc_instan = None
collect_flag = 0
max_wait_time = 1    # 单位分钟

# 读取传感器数据回调
def collected_data_handler(sensor_name=None,**kwargs):
    global sensor_instan
    if not sensor_instan:
        print('sensor is not init')
        return []
    return sensor_instan.read_sensor(sensor_name, **kwargs)
# 返回上位机时间 
def rtc_handler(year=None, month=None, day=None, hour=None, minute=None, second=None):
    global rtc_instan
    # 如果传入了参数，则设置时间
    if year is not None:
        rtc_instan.set_time(year,month,day,hour,minute,second)  # 系统时间
    d = rtc_instan.getRtcTime()
    print("current RTC time:",d)
    return d

def main():
# 变量
    global sensor_instan,max_wait_time
    global rtc_instan,collect_flag
    
# config配置初始化
    app_config.config_init()
# 网络注册
# 初始化系统rtc
    rtc_instan = rtc.SysRtc()
# 创建tf卡接口实例
    tf = tfcard.SetTfCard(rtc_instan)
# 创建串口通信实例
    serial_port232.SerialDrver()
    uart_proj = hmi_drv.HmiDrver()
# 注册串口通信接收数据回调
    uart_proj.register_calback(collected_data_handler)
# 注册触摸屏RTC接口回调
    uart_proj.register_rtc_calback(rtc_handler)
# 获取串口屏RTC时间
    uart_proj.ReadRTC()
# 创建传感器接口实例
    sensor_instan = sensor_interface.SensorInterface()
# 注册传感器参数数据
# 注册电压传感器
    sensor_instan.register_sensor(rm_10=(m485Drv,'read_volt_all_channel'))   # 虚拟函数read_virtual_soil_sensor/实际函数read_soil_sensor
    sensor_instan.register_sensor(flow_10=(m485Drv,'read_flow_caf'))                    
# 主循环
    while True:
        # 读取方式1：读取所有传感器
        # data  = collected_data_handler()
        # 读取方式2：读取特定传感器
        # soil1_data = collected_data_handler('soil1')
        # 读取方式3：临时指定参数（覆盖注册时的参数）
        
        if uart_proj.get_collect_flag():
            data_list = []
            interval = uart_proj.get_interval()  
            time.sleep(interval)
            print("logging")  # 调试信息
            data = collected_data_handler() 
            ch = uart_proj.get_current_channel()
            data_list.extend(data.get('rm_10', []))
            data_list.extend(data.get('flow_10', []))
            data_list.append(ch)
            print(data_list)

        # 存储数据到TF卡
            # csv_header = app_config.read_headers_from_config('rm_header')
            # tf.wirte_to_csv(csv_header,data_list) 

        else:
            # print("collect_flag is False")
            # data = m485Drv.read_flow_caf()
            # print(data)
            time.sleep(3)

        

if __name__ == '__main__':
     main()
